
package com.zcp.pcsuitall.business;

import com.zcp.pcsuitall.Action;
import com.zcp.pcsuitall.BusinessControl;
import com.zcp.pcsuitall.IDealWithMessage;
import com.zcp.pcsuitall.Item;
import com.zcp.pcsuitall.R;
import com.zcp.pcsuitall.SuitUtil;
import com.zcp.pcsuitall.XmlDataDealWith;

import android.content.Context;
import android.database.Cursor;
import android.provider.MediaStore;
import android.util.Log;
import android.util.Xml;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.channels.SocketChannel;
import java.util.Formatter;
import java.util.LinkedList;
import java.util.Locale;

import org.xmlpull.v1.XmlSerializer;

public class MusicManager implements IDealWithMessage {
    private LinkedList<Item> values = null;

    @Override
    public boolean dealWith(SocketChannel sc, Action action, Context context) {

        boolean success = false;
        if (action != null) {
            String op = action.getName();
            if (op.equals("GetMusicInfo")) {
                success = dealWithLoad(sc, action, context);
            } else if (op.equals("DeleteMusic")) {
                success = dealWithDelete(sc, action, context);
            }
        }
        return success;
    }

    LinkedList<MusicObject> musicList = new LinkedList<MusicObject>();;

    /**
     * 获取音乐信息
     * 
     * @param sc
     * @param action
     * @param context
     * @return
     */
    private boolean dealWithLoad(SocketChannel sc, Action action, Context context) {

    	Cursor cursor = null;
        int id = 0;
        String name = "";
        String path = "";
        int timelong = 0;
        String artist = "";
        String album = "";

        /*
         * _ID:id TITLE:name DATA:path DURATION:timelong ARTIST:artist
         * ALBUM:album
         */
        String[] columns = {
                MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE,
                MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.DURATION,
                MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM
        };
        String where = MediaStore.Audio.Media.IS_MUSIC + "=1";

        StringWriter writer = new StringWriter();
        XmlSerializer serializer = Xml.newSerializer();
        
        try {
        	serializer.setOutput(writer);
            XmlDataDealWith.createPre(action, serializer);
            
            cursor = SuitUtil.getMusicInfo(context, columns, where);
            if (cursor != null ) {
            	while (cursor.moveToNext()) {
            		serializer.startTag(null, "item");
                    id = cursor.getInt(cursor.getColumnIndex("_id"));
                    writeSingleTextToXml(serializer, "id", id + "");

                    name = cursor.getString(cursor.getColumnIndex("title"));
                    writeSingleTextToXml(serializer, "name", name);

                    path = cursor.getString(cursor.getColumnIndex("_data"));
                    writeSingleTextToXml(serializer, "path", path);

                    timelong = cursor.getInt(cursor.getColumnIndex("duration"));

                    // 处理播放时长
                    int secs = timelong / 1000;
                    String duration = makeTimeString(context, secs);
                    if (secs == 0) {
                        writeSingleTextToXml(serializer, "timelong", String.valueOf(secs));
                    } else {
                    	writeSingleTextToXml(serializer, "timelong", duration);
                    }

                    artist = cursor.getString(cursor.getColumnIndex("artist"));
                    writeSingleTextToXml(serializer, "artist", artist);

                    album = cursor.getString(cursor.getColumnIndex("album"));
                    writeSingleTextToXml(serializer, "album", album);
                    serializer.endTag(null, "item");
                }
            	cursor.close();
            }
            serializer.text("");
            serializer.endTag("", "data");
            serializer.endTag("", "root");
            serializer.endDocument();
            BusinessControl.returnToClient(sc, writer.toString(), context);
        } catch (Exception e) {
            e.printStackTrace();
            BusinessControl.returnToClient(sc,
                    XmlDataDealWith.getSystemErrorString(action.getName(), e.toString()), context);
            return false;
        } finally {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            writer = null;
            serializer = null;
        }
        return true;
    }

    /**
     * 删除音乐
     * 
     * @param sc
     * @param action
     * @param context
     * @return
     */
    private boolean dealWithDelete(SocketChannel sc, Action action, Context context) {

        values = XmlDataDealWith.getData(new String[] {
                "id", "path"
        }, action.getSource());
        String path = null;

        if (values.isEmpty() || values.get(0).getItemData("id") == null) {
            BusinessControl.returnToClient(sc, XmlDataDealWith.getErrorString(action.getName(),
                    "6", "action deleteMusic id is null"), context);
            return false;
        }
        try {
            for (int i = 0; i < values.size(); i++) {
                if (values.get(i).getItemData("id").equals("")) {
                    continue;
                }
                Log.v(TAG, "delete music id is " + values.get(i).getItemData("id"));
                context.getContentResolver().delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                        "_id=?", new String[] {
                            values.get(i).getItemData("id")
                        });

                path = values.get(i).getItemData("path");
                File f = new File(path);// 从SD卡中删除音乐文件
                try {
                    if (!f.delete()) {
                        Log.e(TAG, "Failed to delete file " + path);
                    }
                    Log.v(TAG, "delete music file is " + values.get(i).getItemData("path"));
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }

            values.clear();
            BusinessControl
                    .returnToClient(
                            sc,
                            "<?xml version=\"1.0\" encoding=\"utf-8\"?><root><action>DeleteMusic</action><data><result>ok</result></data></root>",
                            context);
            return true;
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
            e.printStackTrace();
            BusinessControl.returnToClient(sc,
                    XmlDataDealWith.getSystemErrorString(action.getName(), e.toString()), context);
            BusinessControl
                    .returnToClient(
                            sc,
                            "<?xml version=\"1.0\" encoding=\"utf-8\"?><root><action>DeleteMusic</action><data><result>fail</result></data></root>",
                            context);
            return false;
        }
    }

    private static StringBuilder sFormatBuilder = new StringBuilder();

    private static Formatter sFormatter = new Formatter(sFormatBuilder, Locale.getDefault());

    private static final Object[] sTimeArgs = new Object[5];

    public static String makeTimeString(Context context, long secs) {
        String durationformat = context.getString(secs < 3600 ? R.string.durationformatshort
                : R.string.durationformatlong);

        sFormatBuilder.setLength(0);

        final Object[] timeArgs = sTimeArgs;
        timeArgs[0] = secs / 3600;
        timeArgs[1] = secs / 60;
        timeArgs[2] = (secs / 60) % 60;
        timeArgs[3] = secs;
        timeArgs[4] = secs % 60;

        return sFormatter.format(durationformat, timeArgs).toString();
    }

    /**
     * 创建一个包含单个值的XML节点，如<TAG>value</TAG>,写入serializer中
     * 
     * @param serializer xml写入器
     * @param tag 节点名
     * @param value 节点值
     * @throws IllegalArgumentException
     * @throws IllegalStateException
     * @throws IOException
     */
    private static void writeSingleTextToXml(XmlSerializer serializer, String tag, String value)
            throws IllegalArgumentException, IllegalStateException, IOException {
        // 值为空时不写入XML
        if (value == null)
            value = "";
        serializer.startTag(null, tag);
        serializer.text(value);
        serializer.endTag(null, tag);
    }

    /**
     * 生成返回xml
     * 
     * @param action
     * @return <?xml version="1.0"
     *         encoding="utf-8"?><root><action>action</action
     *         ><data><result>true或false</result></data></root>
     */
    private static String makeReplyCode(String action, boolean result) {
        return String
                .format("<?xml version='1.0' encoding='utf-8'?><root><action>%s</action><data><result>%s</result></data></root>",
                        action, result);
    }
    
    
    private String replaceArtistName(String artist){
    	
    	if(!artist.contains("<")){
    		return artist;
    	}
    	artist = artist.replace("<", "");
    	artist = artist.replace(">", "");
    	return artist;
    }

    public class MusicObject {
        private String id = null;

        private String name = null;

        private String path = null;

        private String timelong = null;

        private String artist = null;

        private String album = null;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getPath() {
            return path;
        }

        public void setPath(String path) {
            this.path = path;
        }

        public String getTimelong() {
            return timelong;
        }

        public void setTimelong(String timelong) {
            this.timelong = timelong;
        }

        public String getArtist() {
            return artist;
        }

        public void setArtist(String artist) {
            this.artist = artist;
        }

        public String getAlbum() {
            return album;
        }

        public void setAlbum(String album) {
            this.album = album;
        }
    }

    private static String TAG = "MusicManager";
}
